package com.dxp.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

//全局异常处理类
@ControllerAdvice(annotations = {RestController.class, Controller.class})  //处理类上有这些注解的类的异常
@ResponseBody  //返回json数据
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException EX){

        if ((EX.getMessage().contains("Duplicate entry")))
        {
            String[] split = EX.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }
    @ExceptionHandler(RuntimeException.class)
    public R<String> exceptionHandler(RuntimeException EX){
       return R.error(EX.getMessage());
    }

}
